#!/bin/sh

# 健康检测脚本
# 功能说明：
#   1.以pid的方式检测应用进程是否存在，如果不存在则认为宕机，exit 1，keepalived进行VIP故障转移
#   2.应用进程存在，且健康接口地址存在，则以curl $health_check_url方式监测接口方式监测是否宕机，如果宕机，exit 1 进行VIP故障转移
# author：huzhijian

#-----------------------------------获取当前脚本路径相关信息---------------------------------------------------
# 判断当前脚本是否为绝对路径，匹配以/开头下的所有
if [ $0 != ^\/.* ]
then
    script=$0
else
    script=$(pwd)/$0
fi

# 获取文件的真实路径
script=`readlink -f $script`
# 获取文件所在的目录
script_path=${script%/*}
# 获取文件所在目录的真实路径
real_path=$(readlink -f $script_path)
# 日志完整路径
log_path=$real_path/log/check_is_alive.log

mkdir $real_path/log
#---------------------------------------------------------------------------------------------------------------

#加载环境变量
profile_path=/etc/pep_mgmt_profile
if [ ! -f "$profile_path" ]; then
    echo "" | sudo tee -a $profile_path > /dev/null
fi
source $profile_path

#需要进行健康检测的应用
service_process_names=pep_mgmt.jar
# 所有程序启动到启动完成后ready所需的毫秒级时间(60秒)
ready_time=60000

#启动时间戳：switch_to_master.sh脚本执行启动程序时，写在profile_path的全局变量中
start_timestamp=${START_TIMESTAMP}

if [ "$start_timestamp"x = ""x ]; then
    # 程序未启动
    exit 0
fi


#获取应用毫秒级启动时间戳
current_timestamp=$(date +%s%3N)
difference = $(($current_timestamp - $start_timestamp))

if [ $(($current_timestamp - $start_timestamp)) -lt $ready_time ]; then
    # 还未启动完成，认为正常，这样做的目的是为了避免程序还未启动完成反复切换
    exit 0
fi


service_process_name_arr=(${service_process_names//,/ }) 
for service_process in ${service_process_name_arr[@]}
do
    # 检测进程是否存在
    software_pid=`ps -ef | grep -v grep | grep $service_process | grep -v check_app_is_alived_work_mode_1.sh | awk '{print $2}'`

    if [ -z "$software_pid" ];then
        # 宕机
        date +"%Y-%m-%d %H:%M:%S $service_process is down, begin to transfer vip" >> $log_path
     
        exit 1
    else
        # 再次通过脚本判断是否正常
        health_check_url='127.0.0.1:8192/pep_mgmt/management/health'
    
        if [ "$health_check_url"x != ""x ]; then
            # 判断status是否是"DOWN"，DOWN:宕机;UP:正常; 这里适用于"spring-boot-starter-actuator"的应用检测，如果不是使用的actuator，判断内容需自己对照修改
            response_body=`curl -m 1 --connect-timeout 2 $health_check_url`
            if [ "$response_body"x != ""x  ]; then
                # 获取json中status的值
                app_status_key="status"
                app_status=""
                #app_status=$(echo "${response_body}" | awk -F "[{,:}]" '{for(i=1;i<=NF;i++){if($i~"'${app_status_key}'"){print $(i+1)}}}' | sed 's/\"//g' | grep DOWN)
                if [ "$app_status"x != ""x  ]; then
                    # 应用宕机
                    date +"%Y-%m-%d %H:%M:%S $service_process is down,begin to transfer vip, health check response:$response_body" >> $log_path
                    exit 1
                fi
            else
                date +"%Y-%m-%d %H:%M:%S $service_process is down,begin to transfer vip, health check response is null" >> $log_path
                exit 1
            fi
        fi
    fi
done


exit 0


